package com.wechat.config.aop;

import com.wechat.core.annotation.LogTime;
import com.wechat.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 响应时间切面
 */
@Aspect
@Slf4j
@Component
@Profile({"dev","prod"})
public class LogTimeAspect {
    
    
    @Pointcut("@annotation(com.wechat.core.annotation.LogTime)")
    public void logTimePointCut() {
    
    }
    
    
    @Around(value = "logTimePointCut()")
    public Object logMethodTimes(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        
        if (!method.isAnnotationPresent(LogTime.class)) {
            try {
                return joinPoint.proceed();
            } catch (Throwable throwable) {
                log.error("执行错误：{}", method.getName());
            }
        }
        
        LogTime annotation = method.getAnnotation(LogTime.class);
        
        try {
            long startTime = System.currentTimeMillis();
            Object proceed = joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            log.info("方法：{}---{},执行时间为：{}", annotation.name(), method.getName(), endTime - startTime);
            return proceed;
        } catch (Throwable throwable) {
            log.error("执行错误：{}", method.getName());
            throw new ServiceException("服务器异常，稍后重试");
        }
        
    }
}
